import { useState, useImperativeHandle, forwardRef } from 'react';
import styles from './index.less';
import { Modal, Table } from 'antd';
import moment from 'moment';
import { connect } from 'umi';
import { tableLocale } from '@/tool/components/PageEmpty';
import { TRMessage } from '#/components';
import { HttpCode } from '#/utils/contacts';
import { operateLogModal, updateIcon } from '@/assets';
import {
  fetchStatusPageViewData,
  asyncUpdateTradeCenterSubmitStatus,
} from '@/pages/Tianji/TenDaysCentralizedBidding/services';

const { Column, ColumnGroup } = Table;

function SubmitStatusModal({ tradeSeqId, menuCode }, ref) {
  useImperativeHandle(ref, () => ({
    initHandle,
  }));

  const [showModal, setShowModal] = useState(false),
    [submitStatusData, setSubmitStatusData] = useState({}),
    [loading, setLoading] = useState(false);

  const initHandle = () => {
    setShowModal(true);
    fetchStatusInfo();
  };

  const fetchStatusInfo = async () => {
    setLoading(true);
    const res = await fetchStatusPageViewData(tradeSeqId, menuCode);
    setLoading(false);
    if (res?.statusCode === HttpCode.SUCCESS) {
      setSubmitStatusData(res.data);
    } else {
      TRMessage.error(res?.message || '获取方案状态信息失败');
    }
  };

  const updateStatus = async () => {
    const res = await asyncUpdateTradeCenterSubmitStatus(tradeSeqId);
    if (res?.statusCode === HttpCode.SUCCESS) {
      TRMessage.success('执行更新动作成功，正在更新中，请稍后重新打开状态查询页面查看最新数据');
    } else {
      TRMessage.error(res?.message || '更新失败');
    }
  };

  return (
    <Modal
      className={styles.submitStatusModal}
      centered={true}
      title={
        <div className={styles.modalTitle}>
          <img src={operateLogModal} />
          <span className={styles.text}>挂单状态</span>
          <div className={styles.unit}>
            <span className={styles.label}>单位(量：</span>MWh{' '}
            <span className={styles.label}>价：</span>元/MWh<span className={styles.label}>)</span>
          </div>
          <div className={styles.update}>
            <img className={styles.icon} src={updateIcon} onClick={updateStatus} />
            <span className={styles.label}>更新时间：</span>
            <span>
              {submitStatusData.updateTime
                ? moment(submitStatusData.updateTime).format('YYYY.MM.DD HH:mm')
                : '-'}
            </span>
          </div>
        </div>
      }
      visible={showModal}
      footer={null}
      onCancel={() => {
        setShowModal(false);
      }}
    >
      <Table
        loading={loading}
        className={styles.table}
        dataSource={submitStatusData.dataSource}
        rowKey="hourOrder"
        bordered={true}
        locale={tableLocale}
        pagination={false}
        scroll={{ x: true }}
      >
        <Column
          title="时点"
          align="center"
          dataIndex="hourOrder"
          key="hourOrder"
          width={76}
          fixed="left"
        />
        {submitStatusData?.columnData?.map((item) => (
          <ColumnGroup title={item.unitTitle} key={item.unitId}>
            <Column
              title={
                <>
                  <div>段一申报</div>
                  <div>(量、价)</div>
                </>
              }
              className={styles.stationsColumn}
              dataIndex={item.unitId + '_firstPower'}
              key={item.unitId + '_firstPower'}
              align="center"
              render={(text, record) => {
                let colorClass = '';
                switch (record[item.unitId + '_tradeType']) {
                  case 0:
                    colorClass = 'green';
                    break;
                  case 1:
                    colorClass = 'red';
                    break;
                  case 2:
                    return <span>-</span>;
                }
                return (
                  <>
                    <span className={styles[colorClass]}>
                      {record[item.unitId + '_firstPower']}
                    </span>
                    、<span>{record[item.unitId + '_firstPrice']}</span>
                  </>
                );
              }}
            />
            <Column
              title={
                <>
                  <div>段二申报</div>
                  <div>(量、价)</div>
                </>
              }
              className={styles.stationsColumn}
              dataIndex={item.unitId + '_secondPower'}
              key={item.unitId + '_secondPower'}
              align="center"
              render={(text, record) => {
                let colorClass = '';
                switch (record[item.unitId + '_tradeType']) {
                  case 0:
                    colorClass = 'green';
                    break;
                  case 1:
                    colorClass = 'red';
                    break;
                  case 2:
                    return <span>-</span>;
                }
                return (
                  <>
                    <span className={styles[colorClass]}>
                      {record[item.unitId + '_secondPower']}
                    </span>
                    、<span>{record[item.unitId + '_secondPrice']}</span>
                  </>
                );
              }}
            />
          </ColumnGroup>
        ))}
      </Table>
    </Modal>
  );
}

export default connect(
  ({ global, tenDaysCentralizedBidding }) => ({
    menuCode: global.configure.menuCode,
    tradeSeqId: tenDaysCentralizedBidding.tradeSeqId,
  }),
  null,
  null,
  { forwardRef: true },
)(forwardRef(SubmitStatusModal));
